package whf.framework.web;

import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import whf.framework.log.Log;
import whf.framework.log.LogFactory;
import whf.framework.security.HibernateSpringUserManager;
import whf.framework.security.UserContext;
import whf.framework.security.UserContextImp;
import whf.framework.security.entity.Role;
import whf.framework.security.entity.User;

/**
 * 提供web上下文系统，植入filter中，当请求发生时使用request初始化
 * @author King
 * @create Feb 3, 2008 2:27:49 PM
 */
public class WebContextHolder {
	private static Log log = LogFactory.getLog(WebContextHolder.class);
	public static final String WEB_CONTEXT_HOLDER_IN_REQUEST = "WEB_CONTEXT_HOLDER_IN_REQUEST";
	private static ThreadLocal<WebContextHolder> context = new ThreadLocal<WebContextHolder>();
	
	private HttpServletRequest request;
	
	public WebContextHolder(HttpServletRequest request) {
		this.request = request;
		this.request.setAttribute(WEB_CONTEXT_HOLDER_IN_REQUEST, this);
		context.set(this);
	}
	
	public static WebContextHolder getWebContext() {
		return context.get();
	}
	
	public static WebContextHolder getWebContext(HttpServletRequest request) {
		return (WebContextHolder)request.getAttribute(WEB_CONTEXT_HOLDER_IN_REQUEST);
	}
	
	public HttpServletRequest getRequest() {
		return this.request;
	}
	
	public HttpSession getSession() {
		return this.request.getSession();
	}

	/**
	 * @return 获取当前用户上下文中的UserContext
	 */
	public UserContext getUserContext(){
		UserContext userContext = (UserContext)request.getSession().getAttribute(UserContext.USER_CONTEXT);
		if(userContext == null){
			try{
				userContext = UserContextImp.createAnonymousUserContext(request);
				request.getSession().setAttribute(UserContext.USER_CONTEXT, userContext);
			}catch(Exception e){
				log.error("Create UserContext", e);
			}
		}
		return userContext;
	}
	
	/**
	 * 创建制定用户的上下文
	 * @param user
	 * @return
	 */
	public UserContext getUserContext(User user) {
		try{
			Set<Role> roles = HibernateSpringUserManager.getUserManager().findRoles(user);
			return UserContextImp.createUserContext(user, roles, this.getSession());
		} catch(Exception e){
			log.error(e);
			return null;
		}
	}
	
	/**
	 * 获取当前用户
	 * @return
	 */
	public User getCurrentUser() {
		UserContext uc = this.getUserContext();
		if(uc != null) {
			return uc.getUser();
		} else{
			return null;
		}
	}
}
